import re;
import string;
from util.En_Formatter import En_Formatter as Formatter;


class En_NgramBuilder(object):
    def __init__(self): 
        self.ngramList = [];
        self.__notList = [".", ",", ";", ":", "\"", "'", "(", ")", "[", "]"];
        
    def __setVars(self, terms):
        self.__terms = terms;
        self.__len = len(terms);
    def run(self, t):
        Ti = 0;
        terms = re.findall(r"\w+(?:[-']\w+)*|'|[-.(]+|\S\w*", t);
        self.__setVars(terms);
        for term in terms:
            self.__ngramBuild(term.title(), 0, Ti);
            Ti += 1;
        # It finishes, and the ngram array is built for use.        
    def __ngramBuild(self, ngram, ngramCount, Ti):
        if(ngramCount == 0):
            if(ngram not in self.__notList):
                self.ngramList.append(ngram);
                self.__ngramBuild(ngram, ngramCount+1, Ti); 
            else:
                #We hit an term that is in notList and need to slide window
                return;   
        elif(ngramCount > 0 and ngramCount < 3):
            #IF there is a next term that we can look at
            if(Ti < self.__len - ngramCount):
                if(self.__terms[Ti + ngramCount] not in self.__notList):
                    ngram = Formatter.termConcat(ngram, (self.__terms[Ti + ngramCount]).title());
                    self.ngramList.append(ngram);
                    self.__ngramBuild(ngram, ngramCount+1, Ti);
                else:
                    #Then we hit a boundary tag and need to stop ngramBuilding and slide window
                    return;
        elif(ngramCount == 3):
            if(Ti < self.__len - ngramCount):
                if(self.__terms[Ti + ngramCount] not in self.__notList):
                    ngram = Formatter.termConcat(ngram, (self.__terms[Ti + ngramCount]).title());
                    self.ngramList.append(ngram);
        else:
            #error...
            return;